package day02;

import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class Demo1_PoolAndTransaction {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //测试连接池
    //分别将SqlMapConfig.xml中的dataSource标签的type改为UNPOOLED和POOLED后执行该测试方法
    @Test
    public void testConnectionPool(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.findAll();
        sqlSession.close();
        //注意查看日志信息中是否有归还连接的操作
    }

    //设置事务自动提交
    @Test
    public void testConnectionAutoCommit(){
        //openSession方法中参数设为true即可实现自动提交（实际开发中很少用）
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(9);
        user.setUsername("嘻嘻哈哈");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("湖北省武汉市xx区xx路1号");
        mapper.updateUser(user);
        //不需要提交事务
        sqlSession.close();
    }
}
